package cn.iborder.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.log.Log;

import cn.iborder.core.ResPool;
import cn.iborder.model.SysLogin;
import cn.iborder.model.SysUser;
import cn.iborder.utils.PubUtil;
import cn.iborder.utils.TrcLog;

public class LoginController extends Controller {
	private Log log = TrcLog.getLogFile();

	public LoginController() {
		// TODO Auto-generated constructor stub
	}
	
	public void index() {
		log.info("[LoginController]index");
		renderJsp("/static/login10086.jsp");
	}
	
	public void code(){
        //产生验证码
        renderCaptcha();
    }

	public void login() {
		log.info("[LoginController]login");
		Date now = new Date();
		//获取请求参数
		String uname = PubUtil.trim(getPara("username"));
		String upass = PubUtil.trim(getPara("password"));
		String code = PubUtil.trim(getPara("code"));
		if (uname.equals("") || upass.equals("") || code.equals("")) {
			//非法访问
			Map<String, Object> json = new HashMap<>();
			json.put("status", false);
			json.put("msg", "小明,妈妈喊你回家吃饭");
			renderJson(json);
			return;
		}

		SysUser sysUser = new SysUser().set("uname", uname).set("upass", upass);
		SysLogin sysLogin = new SysLogin().set("login_name", uname).set("login_pass", upass).set("login_date", now);
		
		//获取当前用户当天登录失败次数,超过10次锁定一天
		int dayLoginFail = getLoginFail(uname);
		if (dayLoginFail >= 10) {
			log.info("[LoginController]当前用户当天登录失败次数超过10次");
			Map<String, Object> json = new HashMap<>();
			json.put("status", false);
			json.put("msg", "当前用户今天登录失败次数超过10次,解锁时间今晚00:00");
			renderJson(json);
			return;
		}
		//获取登录失败次数loginfail
		int loginfail = getSessionAttr("loginfail") == null ? 0 : getSessionAttr("loginfail");
		log.info("[LoginController]登录失败次数:"+loginfail);
		//失败超过5次就锁定当前用户
		if (loginfail >= 5) {
			log.info("[LoginController]登录失败次数大于5");
			//获取解锁时间unlocktime,判断当前用户是否被锁定
			Date unlocktime = getSessionAttr("unlocktime");
			if (unlocktime.after(now)) {
				//未解锁
				//锁定期间每登录一次,解锁时间增加一分钟
				unlocktime.setMinutes(unlocktime.getMinutes() + 1);
				log.info("[LoginController]解锁时间:"+unlocktime.toLocaleString());
				setSessionAttr("unlocktime", unlocktime);
				//sysLogin.set("result", "1").save();
				setLoginFail(uname, dayLoginFail+1, sysLogin);
				Map<String, Object> json = new HashMap<>();
				json.put("status", false);
				json.put("msg", "锁定时间还有" + (unlocktime.getMinutes() - now.getMinutes()) + "分钟,锁定期间请不要尝试登录!");
				renderJson(json);
				return;
			}else {
				//已解锁
				setSessionAttr("loginfail", 0);
			}
		}

		//校验验证码
		if (!validateCaptcha("code")) {
			log.info("[LoginController]验证码校验失败");
			//setLoginFail(uname, dayLoginFail+1, sysLogin);
			Map<String, Object> json = new HashMap<>();
			json.put("status", false);
			json.put("msg", "验证码输入错误");
			renderJson(json);
			return;
		}
		
		//校验用户帐号密码
		log.info("[LoginController]校验用户帐号密码");
		
		if (validateUser(sysUser)) {
			//登录成功
			log.info("[LoginController]登录成功");
			setSessionAttr("loginfail", 0);
			setSessionAttr("loginstatus", "success");
			setSessionAttr("loginuser", uname);
			setLoginFail(uname, 0, sysLogin);
			Map<String, Object> json = new HashMap<>();
			json.put("status", true);
			json.put("msg", "登录成功");
			renderJson(json);
		}else {
			//登录失败
			log.info("[LoginController]登录失败");
			setSessionAttr("loginfail", loginfail+1);
			//登录失败次数达到5次，锁定5分钟
			if (loginfail == 4) {
				log.info("[LoginController]登录失败次数达到5次,锁定5分钟");
				now.setMinutes(now.getMinutes() + 5);
				log.info("[LoginController]解锁时间：:"+now.toLocaleString());
				setSessionAttr("unlocktime", now);
			}
			setSessionAttr("loginstatus", "fail");
			setSessionAttr("loginuser", uname);
			setLoginFail(uname, dayLoginFail+1, sysLogin);
			Map<String, Object> json = new HashMap<>();
			json.put("status", false);
			json.put("msg", "用户名或密码错误");
			renderJson(json);
		}
	}
	
	/**
	 * 获取登录失败次数
	 * @return
	 */
	public int getLoginFail(String uname) {
		String today = PubUtil.trim(JFinal.me().getServletContext().getAttribute("today"));
		String daylogfail = PubUtil.trim(JFinal.me().getServletContext().getAttribute("daylogfail-"+uname+"-"+today));
		//int loginType = PropKit.getInt("loginType");
		int loginType = ResPool.getConfigPool().getInt("loginType");
		//登录类型 1:mysql 2:prop
		if (loginType == 1) {
			List<SysLogin> sysLogins = new SysLogin().find("select * from sys_login where login_name='"+uname+"' and DATE_FORMAT(login_date,'%Y%m%d')='"+today+"' and result='1'");
			return sysLogins.size();
		}else if (loginType == 2) {
			String daylogfailNum = PubUtil.trim(JFinal.me().getServletContext().getAttribute("daylogfail-"+uname+"-"+today));
			if ("".equals(daylogfailNum)) {
				daylogfailNum = "0";
			}
			return Integer.parseInt(daylogfailNum);
		}else{
			throw new RuntimeException("登录类型未设置");
		}
	}
	
	/**
	 * 设置失败次数
	 * @return
	 */
	public void setLoginFail(String uname, int daylogfailNum, SysLogin sysLogin) {
		log.info("[LoginController.setLoginFail]"+uname+"当天登录失败次数:"+daylogfailNum);
		String today = PubUtil.trim(JFinal.me().getServletContext().getAttribute("today"));
		//int loginType = PropKit.getInt("loginType");
		int loginType = ResPool.getConfigPool().getInt("loginType");
		//登录类型 1:mysql 2:prop
		if (loginType == 1) {
			sysLogin.set("result", "1").save();
		}else if (loginType == 2) {
			JFinal.me().getServletContext().setAttribute("daylogfail-"+uname+"-"+today, daylogfailNum);
		}else{
			throw new RuntimeException("登录类型未设置");
		}
	}
	
	/**
	 * 验证用户
	 * @param sysUser
	 * @return 验证成功true 失败false
	 */
	public boolean validateUser(SysUser sysUser) {
		log.info("[LoginController.getLoginFail]验证用户");
		//int loginType = PropKit.getInt("loginType");
		int loginType = ResPool.getConfigPool().getInt("loginType");
		//String sysUsers = PubUtil.trim(PropKit.get("sysUsers"));
		String sysUsers = ResPool.getConfigPool().getString("sysUsers");
		if ("".equals(sysUsers)) {
			throw new RuntimeException("系统用户未配置");
		}
		//登录类型 1:mysql 2:prop
		if (loginType == 1) {
			SysUser user = new SysUser().findFirst("select * from sys_user where uname='"+sysUser.getUname()+"' and upass='"+sysUser.getUpass()+"'");
			if (user != null) {
				return true;
			}
		}else if (loginType == 2) {
			if (sysUsers.contains(sysUser.getUname()+"-"+sysUser.getUpass()+"&&")) {
				return true;
			}
		}else{
			throw new RuntimeException("登录类型未配置");
		}
		return false;
	}

}
